<?php
/**
 * 团队页面API接口
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

session_start();

// 引入必要的文件
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/team_data.php';
require_once __DIR__ . '/../config/team_config.php';

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    $teamManager = new TeamDataManager($pdo, $user_id);
    $config = include __DIR__ . '/../config/team_config.php';
    
    switch ($action) {
        case 'get_stats':
            $stats = $teamManager->getTeamStats();
            echo json_encode(['success' => true, 'data' => $stats]);
            break;
            
        case 'get_members':
            $page = (int)($_GET['page'] ?? 1);
            $limit = (int)($_GET['limit'] ?? $config['pagination']['team_members_limit']);
            $offset = ($page - 1) * $limit;
            
            $members = $teamManager->getTeamMembers($limit, $offset);
            echo json_encode(['success' => true, 'data' => $members]);
            break;
            
        case 'get_commissions':
            $limit = (int)($_GET['limit'] ?? $config['pagination']['commissions_limit']);
            $commissions = $teamManager->getRecentCommissions($limit);
            echo json_encode(['success' => true, 'data' => $commissions]);
            break;
            
        case 'refresh_qr':
            $user = $teamManager->getUserInfo();
            $invite_link = $teamManager->getInviteLink($user);
            echo json_encode(['success' => true, 'data' => ['invite_link' => $invite_link]]);
            break;
            
        case 'get_invite_info':
            $user = $teamManager->getUserInfo();
            $invite_link = $teamManager->getInviteLink($user);
            echo json_encode([
                'success' => true, 
                'data' => [
                    'invite_code' => $user['invite_code'] ?? '',
                    'invite_link' => $invite_link
                ]
            ]);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => '无效的操作']);
            break;
    }
    
} catch (Exception $e) {
    error_log("团队API错误: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => '服务器内部错误']);
}
?>
